package com.clement.spring.study.validator;

import com.clement.spring.study.model.Person;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by Clement on 2017/2/28.
 */
public class PersonValidator implements Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "name", "name.empty");
        Person person = (Person) target;
        if (person.getAge() < 0)
            errors.rejectValue("age", "negative value");
        else if (person.getAge() > 110)
            errors.rejectValue("age", "not likely too old");
    }
}
